/**
 * Gmini.vue - Gemini AI聊天组件
 * 提供与后端API的聊天界面
 */

<script setup>

import { defineOptions } from 'vue'

defineOptions({
  name: 'Gmini'
})

import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ChatDotRound, ChatLineRound, Service, User, Position, Loading } from '@element-plus/icons-vue';
import { createUserMessage, createAssistantMessage, sendMessage as sendGminiMessage } from '../services/gminiService';

// 组件状态
const messages = ref([]); // 聊天消息历史
const inputMessage = ref(''); // 用户输入
const loading = ref(false); // 加载状态
const messageContainerRef = ref(null); // 消息容器引用
const chatTopic = ref(''); // 当前聊天主题

// 添加延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 在 ChatGPT.vue 中添加
import { onActivated, onDeactivated } from 'vue';
// import { console } from 'inspector';

// 组件被激活时触发
onActivated(() => {
  console.log('Gmini Component activated');
  nextTick(() => {
    if (messageContainerRef.value) {
      messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
    }
  });
});

// 组件被停用时触发
onDeactivated(() => {
  console.log('Component deactivated');
  // 可以在这里处理一些停用时的逻辑
});

/**
 * 发送消息到后端API
 * @param {string} content - 用户输入的消息内容
 */
const handleSendMessage = async (content) => {
  if (!content.trim() || loading.value) return;

  try {
    loading.value = true;
    
    // 添加1秒延迟
    await delay(1000);

    // 添加用户消息
    const userMessage = createUserMessage(content);
    messages.value.push(userMessage);

    // 更新聊天主题
    if (messages.value.length === 1) {
      chatTopic.value = content.slice(0, 10) + (content.length > 10 ? '...' : '');
    }

    // 发送消息到 Gmini API
    const response = await sendGminiMessage(content);

    // 添加 AI 回复
    if (response && response.choices && response.choices[0]) {
      messages.value.push(createAssistantMessage(response.choices[0].message.content));
      console.log("Gminiresponse:",response)
    } else {
      console.log("response:",response)
      throw new Error(response.error,response.details );
    }

    // 清空输入框
    inputMessage.value = '';

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('发送消息错误:', error);
    ElMessage.error(error.message || '发送消息失败，请重试');
    // 移除失败的消息
    messages.value.pop();
  } finally {
    loading.value = false;
  }
};

/**
 * 处理键盘事件
 * @param {Event} event - 键盘事件对象
 */
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    handleSendMessage(inputMessage.value);
  }
};

/**
 * 滚动消息容器到底部
 */
const scrollToBottom = () => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
  }
};

// 组件挂载时初始化
onMounted(() => {
  if (messageContainerRef.value) {
    messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
  }
});
</script>

<template>
  <div class="chat-container">
    <!-- 聊天主题 -->
    <div v-if="chatTopic" class="chat-topic">
      <el-icon ><ChatDotRound /></el-icon>
      <span>当前话题: {{ chatTopic }}</span>
    </div>

    <!-- 消息列表 -->
    <div ref="messageContainerRef" class="message-container">
      <template v-if="messages.length === 0">
        <div class="welcome-message">
          <el-icon class="service-icon"><Service /></el-icon>
          <h2>欢迎使用 Gemini AI 助手 gemini-pro ·免开VPN</h2>
          <p>我是 Google 开发的新一代 AI 助手，可以帮助你回答问题、编写代码、解决问题等。</p>
          <p>请在下方输入你的问题，按Enter发送。</p>
        </div>
      </template>
      <template v-else>
        <div v-for="(message, index) in messages" 
             :key="index" 
             :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-avatar">
            <el-icon :size="36"> 
              <!-- <component :is="message.role === 'user' ? User : message.role === 'assistant' ? Service : null" /> -->
              <component :is="message.role === 'user' ? 'User' : message.role === 'assistant' ? 'Service' : null" />
            </el-icon>
          </div>
          <div class="message-content" style="height: 100%;" >
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
          
          </div>
        </div>
      </template>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        :placeholder="loading ? '正在思考中...' : '输入消息，按Enter发送，Shift+Enter换行'"
        @keydown="handleKeyPress"
        :disabled="loading"
        resize="none"
      >
        <template #prefix>
          <el-icon><ChatLineRound /></el-icon>
        </template>
      </el-input>
      <el-button 
        type="primary" 
        @click="handleSendMessage(inputMessage)"
        :loading="loading"
        :disabled="!inputMessage.trim() || loading"
      >
        <el-icon v-if="!loading"><Position /></el-icon>
        <el-icon v-else><Loading /></el-icon>
        <span>{{ loading ? '思考中...' : '发送' }}</span>
      </el-button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 95%;
  /* max-height: 110%; */
  max-height: calc(100% - 20px);
  padding: 0.2rem;
  gap: 1rem;
  /* max-width: 800px; */
  margin: 0 auto;
  margin-top: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-topic {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.welcome-message {
  text-align: center;
  color: #606266;
  padding: 2rem;
}

.welcome-message .el-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 1rem;
}

.message {
  display: flex;
  gap: 1rem;
  max-width: 93%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.message-avatar {
  flex-shrink: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-message .message-avatar {
  background-color: #409eff;
  color: white;
}

.message-content {
  background-color: #f5f7fa;
  padding: 0.8rem;
  border-radius: 8px;
  position: relative;

}

.user-message .message-content {
  background-color: #409eff;
  color: white;
  padding: 5px 10px;
}

.message-text {
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 12px;
}

.message-time {
  font-size: 0.75rem;
  color: #909399;
  margin-top: 0.25rem;
}

.user-message .message-time {
  color: #e6e6e6;
}

.input-container {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.input-container .el-input {
  flex: 1;
}

/* 滚动条样式 */
.message-container::-webkit-scrollbar {
  width: 6px;
}

.message-container::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.message-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 移动端和竖屏适配 */
@media (max-width: 768px) {
  .chat-container {
    height: calc(100vh - 120px);
    margin: 10px;
    padding: 0.5rem;
  }

  .message {
    max-width: 90%;
  }

  .input-container {
    padding: 0.5rem;
  }
}
</style>
